package com.tcoiss.common.core.exception;

import com.tcoiss.common.core.enums.ErroEnums;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

/**
 * 自定义异常
 * 
 * @author tcoiss
 */
public class CustomException extends RuntimeException
{
    private static final long serialVersionUID = 1L;

    private static final Object[] empty_args = new Object[0];

    private Integer code;

    private String message;

    private Object[] args;

    public CustomException(String message)
    {
        this.message = message;
    }

    public CustomException(String message, Integer code)
    {
        this.message = message;
        this.code = code;
    }

    public Object[] getArgs() {
        return this.args == null ? empty_args : this.args;
    }

    public void setArgs(Object[] args) {
        this.args = args;
    }

    public CustomException(String message, Throwable e)
    {
        super(message, e);
        Writer result = new StringWriter();
        PrintWriter printWriter = new PrintWriter(result);
        this.printStackTrace(printWriter);
        printWriter.flush();
        this.code = ErroEnums.BUSERRO.getCode();
        this.message = message + result.toString();
        this.args = empty_args;
    }

    public CustomException(Integer code,String message, Throwable e)
    {
        super(message, e);
        Writer result = new StringWriter();
        PrintWriter printWriter = new PrintWriter(result);
        e.printStackTrace(printWriter);
        this.code = code;
        this.message = message + result.toString();
        this.args = null;
    }

    public CustomException(Throwable cause, String message, Object... args) {
        super(message, cause);
        this.message = message;
        this.args = args;
    }

    public CustomException(String message, String arg, Throwable cause) {
        this(cause, message, new Object[]{arg});
    }

    public CustomException(Integer code,Object[] args,String message)
    {
        this.args = args;
        this.code = code;
        this.message = message;
    }

    public Integer getCode()
    {
        return code;
    }


    public String getMessage() {
        return this.message != null && this.message != ""
                ? this.format(this.message)
                : super.getMessage();
    }

    private String format(String msg) {
        if (this.args != null && this.args.length != 0) {
            try {
                return String.format(msg, this.args);
            } catch (Exception arg2) {
                return msg;
            }
        } else {
            return msg;
        }
    }
}
